package io.renren.modules.websocket;

import io.renren.common.exception.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/18 13:33
 * @Version 1.0
 */
@Component
public class MessageModule {
    @Autowired
    private WebSocketServer webSocketServer;
    public boolean sendMessageToAll(String message) throws IOException {
        try {
            String msg = message+"|0";
            webSocketServer.onMessage(msg,null);
        }catch (RRException e){
            throw new RRException("websocket出现异常");
        }
        return true;
    }

    public boolean sendMessageToSomeone(String message,String userId){
        String msg =message+"|"+userId;
        try {
            WebSocketServer webSocketServer1 = webSocketServer.getWebSocketSessions().get(userId);
            if(webSocketServer1!=null){
                Session session1 = webSocketServer1.getSession();
                webSocketServer.onMessage(msg,session1);
            }else {
                return false;
            }
        }catch (RRException e){
            throw new RRException("websocket出现异常");
        }
        return true;
    }
}
